import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getWebHome } from '@/api/home'
import { resetRouter } from '@/router'
import { ParamArr, SQLTable } from '../../../public/js/paramarr'

const getDefaultState = () => {
  return {
    token: getToken('Token'),
    name: '',
    avatar: '',
    title: '',
    list: [],
    userID: '',
    userName: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_TITLE: (state, title) => {
    state.title = title
  },
  SET_LIST: (state, list) => {
    state.list = list
  },
  SET_USERID: (state, id) => {
    state.userID = id
  },
  SET_USERNAME: (state, name) => {
    state.userName = name
  }
}

const actions = {
  // user login
  login({ commit }, vPar) {
    return new Promise((resolve, reject) => {
      login(vPar).then(vPar => {
        commit('SET_TOKEN', vPar.getStr('Token'))
        commit('SET_NAME', vPar.getStr('User'))
        commit('SET_TITLE', vPar.getStr('SysLogo'))
        setToken('Token', vPar.getStr('Token'))
        setToken('roleIds', vPar.getStr('UserRoleIDs'))
        sessionStorage.setItem('loginID', vPar.getStr('LoginID'))
        sessionStorage.setItem('user', vPar.getStr('User'))
        sessionStorage.setItem('eds', vPar.getStr('PassDES'))
        sessionStorage.setItem('deskey', vPar.getStr('Key'))
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit }, vPar) {
    return new Promise((resolve, reject) => {
      getInfo(vPar).then(vPar => {
        // if (!data) {
        //   return reject('Verification failed, please Login again.')
        // }
        var titleObj = { '标准版本': 'KC-AOM', '制品库': '制品库管理系统' }
        commit('SET_TITLE', titleObj[vPar.getStr('SysLogo')] || vPar.getStr('SysLogo').toLocaleUpperCase())
        commit('SET_NAME', vPar.getStr('UserID'))
        // commit('SET_AVATAR', avatar)
        resolve(vPar)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getWebHome({ commit }) {
    getWebHome(new ParamArr()).then(vPar => {
      commit('SET_USERID', vPar.getStr('UserID'))
      commit('SET_USERNAME', vPar.getStr('UserName'))
      sessionStorage.setItem('sysLogo', vPar.getStr('SysLogo'))

      const nodes = []
      const table = new SQLTable(vPar.getTable('k_menu'))
      table.first()
      while (!table.eof()) {
        const node = {}
        // data
        node.id = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node.title = table.getValueByName('title')
        node.icon = table.getValueByName('icon')
        node.url = table.getValueByName('url')
        node.aLevel = table.getValueByName('aLevel')
        node.sort = table.getValueByName('Sort')
        node.count = table.getValueByName('Count')
        node.timeFlag = table.getValueByName('TimeFlag')
        // next
        nodes.push(node)
        table.next()
      }
      // const obj = {}
      // nodes.forEach(item => {
      //   item.url && (obj[item.url] = item.title)
      // })
      // console.log(JSON.stringify(obj))

      // window.k_menu = nodes
      // window.obj = obj
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

